<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- 搜索 -->
      <!-- 索赔单查询--厂端 -->
      <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
      <!-- table -->
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :dataSource="dataList"
        :fetchapi="fetchApi"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        :is-select-column="false"
        columnsRef="ClaimQueryFactorylgr"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="exportFileBtn.bind()">导出</multiuse-button>
          <!--        <multiuse-button size="small">导入</multiuse-button>-->
        </template>
      </FilterTable>
      <BaseDialog :visible.sync="visible" :title="'车型选择'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <ModelVehicle @close="close" @save="save"></ModelVehicle>
      </BaseDialog>
      <Drawer :visible.sync="visibleEdit" :title="'索赔查看'" destroyOnClose width="100%" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <editForm @close="editclose" @save="editsave" :rowData="rowData" :isDetailed="isDetailed"></editForm>
      </Drawer>
      <!--  服务中心选择 -->
      <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
        <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
      </BaseDialog>
    </div>
  </Spin>
</template>
<script>
import { getClaimCheckReport,getListForExport} from '@/api/claim/factory/ClaimCheckReport/index';
import ModelVehicle from '@/pages/claimDemage/tools/ModelVehicle.vue';
import { exportExcelFile } from '@/utils/index';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index';//事业部，办事处
import {getModelAll} from '@/api/cms-common/basedata';
export default {
  name:'ClaimCheckReport',
  mixins: [dictionary],
  components: {
    ModelVehicle,
    DealerList,
  },
  data() {
    return {
      // 非单个禁用
      // single: true,
      single: false,
      // 非多个禁用
      multiple: true,
      dealerList: [],
      selectDelearFlag: false,
      dealerCompanyCode: [],
      dealerData: [],
      selectDealerData: [],
      loading: false,
      dataList: [],
      boHuiAdd: false,
      visible: false,
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      suppliers:false,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      fetchApi: getClaimCheckReport,
      columns: this.creatHeader(),
      fetchParams: {xhrAbort: true,moveFlag:1 }, //ipa 接口
      selectedRows: [], //选中服务中心
      dialogTitle: '选择车辆',
      visibleAdd: false,
      visibleEdit: false,
      rowData: {},
      isDetailed:null,
      ORG_TYPE_SERVICE_WAR_AREA:15061019, //服务战区
      ORG_TYPE_SERVICE_BIG_AREA:15061020, //服务大区
      ORG_TYPE_SERVICE_SMALL_AREA:15061021, //服务小区
    };
  },
  created() {

    this.fetchParams.beginDate = moment()
      .startOf('week')
      .format('YYYY-MM-DD HH:mm:ss');
    this.fetchParams.endDate = moment()
      .endOf('week')
      .format('YYYY-MM-DD HH:mm:ss');
    this.chuqi();
  },
  mounted(){
    this.getTopLevelArea(this.ORG_TYPE_SERVICE_WAR_AREA,'serviceWarArea');
  },
  methods: {
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'SELECT', label: '服务战区', fieldName: 'serviceWarArea', placeholder: '请选择', initialValue: ''
          ,itemList: [],
          change: val => {
            this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_SERVICE_BIG_AREA,
              'serviceWarArea','serviceBigArea','serviceSmallArea');
          },
        },
        { type: 'SELECT', label: '服务大区', fieldName: 'serviceBigArea', placeholder: '请选择', initialValue: ''
          ,itemList: [],
          change: val => {
            this.changeTopAndMiddleLevelArea(val,this.ORG_TYPE_SERVICE_SMALL_AREA,
              'serviceBigArea','serviceSmallArea','serviceSmallArea');
          },
        },
        { type: 'SELECT', label: '服务小区', fieldName: 'serviceSmallArea', placeholder: '请选择', initialValue: ''
          ,itemList: [],
        },
        {
          type: 'SELECT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => this.selectDelearFlag = true} />
              </div>
            );
          },
          onChange: val => {
            console.log(val)
          }
        },
        {
          type: 'RANGE_DATE',
          label: '日期',
          fieldName: 'beginDate|endDate',
          placeholder: '请输入',
          initialValue: [
            moment(new Date()).subtract(1,'months')
              .format("YYYY-MM-DD"),
            moment(new Date())
              .format("YYYY-MM-DD")
          ],
          // maxDateTime:moment().subtract(1,'days'),
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        { type: 'SELECT', label: '车型名称', fieldName: 'modelCode', placeholder: '请选择', initialValue: '', itemList: this.getModel() },

        ,
      ];
    },
    //搜索获取数据
    changeHandle(val) {

      val.beginDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[0];
      val.endDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[1];
      if(val.beginDate) {
        val.beginDate = moment(val.beginDate).format('YYYY-MM-DD HH:mm:ss');
      }
      if(val.endDate) {
        val.endDate = moment(val.endDate).format('YYYY-MM-DD HH:mm:ss');
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null, xhrAbort: false,moveFlag:1  });
      // this.SELECT();
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '车型', dataIndex: 'modelName', sorter: true },
        { title: '服务战区', dataIndex: 'serviceWarAreaName', sorter: true },
        { title: '服务大区', dataIndex: 'serviceBigAreaName', sorter: true },
        { title: '服务小区', dataIndex: 'serviceSmallAreaName', sorter: true },
        { title: '服务中心代码', dataIndex: 'dealerCode', sorter: true },
        { title: '服务中心名称', dataIndex: 'dealerName', sorter: true },
        { title: '进站数', dataIndex: 'vinNum', sorter: true },
        {
          title: '工单',
          align: 'center',
          children: [
            {
              title: '日新增',
              align: 'center',
              dataIndex: 'todayRoNum',
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'totalRoNum'
            },
            {
              title: '结算金额',
              align: 'center',
              dataIndex: 'totalSettleAmount'
            }
          ]
        },
        {
          title: '索赔单申请数',
          align: 'center',
          children: [
            {
              title: '今日新增',
              align: 'center',
              dataIndex: 'todayClNum',
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'totalClNum'
            }
          ]
        },
        {
          title: '索赔申请单审核',
          align: 'center',
          children: [
            {
              title: '今日新增',
              align: 'center',
              dataIndex: 'todayCkNum',
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'totalCkNum'
            }
          ]
        },
        {
          title: '索赔申请单审核费用',
          align: 'center',
          children: [
            {
              title: '今日新增',
              align: 'center',
              dataIndex: 'todayCkAmount',
            },
            {
              title: '累计',
              align: 'center',
              dataIndex: 'totalCkAmount'
            }
          ]
        },
        { title: '索赔单上传及时率%', dataIndex: 'inTimeRate', sorter: true },
        {
          title: '一次通过率%',
          align: 'center',
          children: [
            {
              title: '考评',
              align: 'center',
              dataIndex: 'onceAgreeRate',
            },
            {
              title: '全量',
              align: 'center',
              dataIndex: 'onceAgreeTotalRate'
            }
          ]
        },
        { title: '通过数', dataIndex: 'agreeClNum', sorter: true },
        { title: '驳回数', dataIndex: 'rejectClNum', sorter: true },
        { title: '作废数', dataIndex: 'cancelClNum', sorter: true },
        { title: '拒赔数', dataIndex: 'refuseClNum', sorter: true },
        { title: '拒赔金额', dataIndex: 'refuseClAmount', sorter: true },
        { title: '拒赔率(单数)%', dataIndex: 'refuseNumRate', sorter: true },
        { title: '拒赔率(金额)%', dataIndex: 'refuseAmountRate', sorter: true }

      ];
    },
    async chuqi() {
      console.log('进来了');

    },
    //获取所有车型
    async getModel() {
      let res = await getModelAll();
      if (res.resultCode === 200) {
        this.topFilterInit.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({text:x.modelName,value:x.modelCode}));

      }
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterInit.find(item => item.fieldName === filedName).itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },

    //顶层和中层组织数据修改
    async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName,smallFieldName, flag = true) {
      let sonArea = this.topFilterInit.find(item => item.fieldName === sonFieldName);
      let smallArea = this.topFilterInit.find(item => item.fieldName === smallFieldName);
      if (!deptId) {
        sonArea.initialValue = '';
        sonArea.itemList = [];
        smallArea.initialValue = '';
        smallArea.itemList = [];
      } else {
        if (flag) {
          //正常的级联，清空原来选择的数据
          sonArea.initialValue = '';
          smallArea.initialValue = '';
        }
        const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
        if (res.resultCode === 200) {
          sonArea.itemList = res.data.map(x => ({ value: parseInt(x.id), text: x.orgName }));
        }
      }
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.topFilterInit.find(x => x.fieldName == 'serviceBigArea').itemList =[];
      this.topFilterInit.find(x => x.fieldName == 'serviceSmallArea').itemList =[];

      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },

    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    close(val, data) {
      if (data) {
        let dealerCodes = [];
        data.map(x => {
          dealerCodes.push(x.modelCode);
        });
        this.topFilterInit.find(x => x.fieldName == 'modelCodeStr').initialValue = dealerCodes.toString();
      }
      this.visible = false;
    },
    chooseOrderNo() {
      this.visible = true;
    },
    chooseDealerNo() {
      this.visibleAdd = true;
    },
    //服务中心选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach(item => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
    save(obj) {
      this.topFilterInit.find(x => x.fieldName == 'modelCode').initialValue = obj[0].modelCode;
      this.visible = false;
    },
    async exportFileBtn() {
      // let json = Object.assign({}, { CODE: 'CODE_00000140' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      let beginDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[0];
      let endDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[1];
      if (!beginDate) {
        this.$notify.warning({ title: '提示信息', message: '开始日期不可为空！' });
        return;
      }
      if (!endDate) {
        this.$notify.warning({ title: '提示信息', message: '结束日期不可为空！' });
        return;
      }

      let obj = Object.assign({}, this.fetchParams, { techStatusStrs: '55131002, 55131003, 55131005,55131004,55131006,55131007,55131008',dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null, xhrAbort: false });

      obj.beginDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[0];
      obj.endDate = this.topFilterInit.find(x => x.fieldName == 'beginDate|endDate').initialValue[1];

      if(obj.beginDate) {
        obj.beginDate = moment(obj.beginDate).format('YYYY-MM-DD HH:mm:ss');
      }
      if(obj.endDate) {
        obj.endDate =  moment(obj.endDate).format('YYYY-MM-DD HH:mm:ss');
      }
      this.loading = true;
      getListForExport(obj).then(res => {
        exportExcelFile(res.data, '索赔单审核报表');
        this.loading = false;
      });
    },
    add() {
      this.visibleAdd = true;
    },
    // saveAdd() {
    //   this.visibleAdd = false;
    //   this.fetchParams = { ...this.fetchParams };
    // },
    editclose() {
      this.visibleEdit = false;
      this.isDetailed = false;
    },
    edit(val) {
      this.rowData = val;
      this.visibleEdit = true;
      this.isDetailed = true;

    },

    editsave() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    }

  }
  // mounted() {
  //   this.BaseTable = this.$refs.listModal.$refs.pageTable;
  // }
};
</script>

<style lang="less" scoped></style>
